package org.example.https;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.security.KeyStore;

/**
 * @author hh
 * @since 2025/2/16
 */
public class SSLContextFactory {
    public static SSLContext getSslContext() throws Exception{
        // 加载密钥库
        String pass = "123456";
        String keyStoreFile = "/Users/hh/test/server.jks";
        char[] passArray = pass.toCharArray();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        // 加载keyStoreFile，生成的密钥仓库
        try (FileInputStream fis = new FileInputStream(keyStoreFile)){
            keyStore.load(fis, passArray);
        }

        // 初始化密钥管理器工厂
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, passArray);

        // 初始化信任管理器工厂（可选，如果需要验证客户端证书）
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        // 初始化SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        return sslContext;
    }
}
